package com.dlc.yunguang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.base.Constants;
import com.dlc.yunguang.net.bean.DepartmentsBean;
import com.dlc.yunguang.net.bean.HospitalBean;
import com.dlc.yunguang.net.bean.ProductListBean;
import com.dlc.yunguang.net.bean.SimpleBean;
import com.dlc.yunguang.net.bean.SpecListBean;
import com.dlc.yunguang.net.bean.UserBean;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.TagProto;
import com.dlc.yunguang.R;

import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BindTagActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.item_rfid_amount)
    CommonItemView mItemRfidAmount;
    //@BindView(R.id.item_name)
    //CommonItemView mItemName;
    @BindView(R.id.tv_spec)
    TextView mTvSpec;
    @BindView(R.id.drop_spec)
    FrameLayout mDropSpec;
    @BindView(R.id.item_spec)
    CommonItemView mItemSpec;
    @BindView(R.id.btn_bind)
    Button mBtnBind;

    @BindView(R.id.tv_user)
    TextView mTvUser;
    @BindView(R.id.drop_user)
    FrameLayout mDropUser;
    @BindView(R.id.item_user)
    CommonItemView mItemUser;
    @BindView(R.id.tv_departments)
    TextView mTvDepartments;
    @BindView(R.id.drop_departments)
    FrameLayout mDropDepartments;
    @BindView(R.id.item_departments)
    CommonItemView mItemDepartments;
    @BindView(R.id.tv_Hospital)
    TextView mTvHospital;
    @BindView(R.id.drop_Hospital)
    FrameLayout mDropHospital;
    @BindView(R.id.item_Hospital)
    CommonItemView mItemHospital;
    
    @BindView(R.id.tv_productName)
    TextView mTvProductName;
    @BindView(R.id.drop_product)
    FrameLayout mDropProduct;



    private CommonPopupList mSpecPopup;//分类规格
    private CommonPopupList mProductPopup;//产品
    private CommonPopupList mHospitalPopup;//医院
    private CommonPopupList mUserPopup;//个人
    private CommonPopupList mDepartmentsPopup;//科室

    private ArrayList<String> mRfids;

    List<SpecListBean.DataBean> specList;
    private Integer specId = null;

    List<ProductListBean.DataBean> productList;
    private Integer productId = null;

    List<HospitalBean.DataBean> HospitalList;
    private Integer HospitalId = null;

    List<DepartmentsBean.DataBean> DepartmentsList;
    private Integer DepartmentsId = null;

    List<UserBean.DataBean> UserList;
    private Integer UserId = 0;

    private Integer MerchantId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        resovleIntent();
        mTitleBar.leftExit(this);
        mItemRfidAmount.setContent(String.valueOf(mRfids.size()));
        initView();
        initPopupList();
       // initDepartments();
        initHospitalList();
       // initUser();
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_bind_tag;
    }

    @OnClick({ R.id.drop_spec, R.id.btn_bind, R.id.drop_departments,R.id.drop_Hospital, R.id.drop_user })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.drop_spec:
                mSpecPopup.showAsDropDown(view);
                break;
            case R.id.drop_Hospital:
                mHospitalPopup.showAsDropDown(view);
                break;
            case R.id.drop_user:
                mUserPopup.showAsDropDown(view);
                break;
            case R.id.drop_departments:
                mDepartmentsPopup.showAsDropDown(view);
                break;
            case R.id.btn_bind:
                doBind();
                break;
        }
    }

    private void resovleIntent() {
        Intent intent = getIntent();
        mRfids = intent.getStringArrayListExtra(TagManageActivity.EXTRA_RFIDS);
    }

    /**
     * 开始绑定
     */
    private void doBind() {

        if (productId == null) {
            showToast("请选择产品!");
            return;
        }
        if (DepartmentsId == null) {
            showToast("请选择科室!");
            return;
        }
        final DoResultDialog doResultDialog = DoResultDialog.newDialog(this)
            .setSuccessImage(R.mipmap.ic_success)
            .setWorkingText(getString(R.string.commit_binding))
            .setSuccessText(getString(R.string.commit_binding_success));

        doResultDialog.setCancelable(false);

        doResultDialog.showWorking();

        // TODO: 2017/7/26 这里标签的数据都是假的 
        TagProto.get()
            .bindRFID(productId, DepartmentsId,UserId, mRfids.toArray(new String[mRfids.size()]))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<SimpleBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    doResultDialog.dismiss();
                    showToast("绑定失败," + e.getMessage());
                }

                @Override
                public void onNext(SimpleBean simpleBean) {
                    doResultDialog.showResultAndRun(true, new Runnable() {
                        @Override
                        public void run() {
                            doResultDialog.dismiss();
                            finish();
                        }
                    }, 1000);
                }
            });
    }

    /**
     * 初始化下拉列表
     */
    //private CommonPopupList mSpecPopup;//分类规格 ----科室
    //private CommonPopupList mHospitalPopup;//医院
    //private CommonPopupList mUserPopup;//个人
    //private CommonPopupList mDepartmentsPopup;//科室
    private void initView() {
        mSpecPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropSpec)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    mTvSpec.setText(item);

                    specId = specList.get(position).getId();
                    initProductPopupList(specId);
                    mTvProductName.setText("");
                }
            })
            .build();
        mProductPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropProduct)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvProductName.setText(item);
                    productId = productList.get(position).getId();
                    int type = productList.get(position).type;
                    if (type == 1){
                        mItemUser.setVisibility(View.VISIBLE);
                    }else {
                        UserId = 0;
                        mItemUser.setVisibility(View.GONE);
                    }
                }
            })
            .build();

        mHospitalPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropHospital)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvHospital.setText(item);
                    HospitalId = Integer.valueOf((HospitalList.get(position).id));
                    initDepartments(HospitalId);
                    mTvDepartments.setText("");
                }
            })
            .build();

        mDepartmentsPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropDepartments)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvDepartments.setText(item);
                    DepartmentsId = Integer.valueOf(DepartmentsList.get(position).id);
                    initUser(HospitalId,DepartmentsId);
                    mTvUser.setText("");
                }
            })
            .build();
        mUserPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropUser)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvUser.setText(item);
                    UserId = Integer.valueOf(UserList .get(position).id);
                }
            })
            .build();
    }

    /**
     * 初始化规格下拉
     */
    private void initPopupList() {
        StockProto.get()
            .spec("", "", "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<SpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(SpecListBean bean) {
                    specList = bean.data;
                    if (specList != null) {
                        String[] descNames = new String[specList.size()];
                        for (int i = 0; i < specList.size(); i++) {
                            descNames[i] = specList.get(i).getName();
                        }
                        setPopupData(Constants.ITEM_TYPE.SPEC, descNames);
                    }
                }
            });
    }

    /**
     * 初始化产品下拉
     */
    private void initProductPopupList(int cateGoryId) {
        StockProto.get()
            .goods1(cateGoryId, "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<ProductListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(ProductListBean bean) {
                    productList = bean.data;

                    if (productList != null) {
                        String[] productNames = new String[productList.size()];
                        for (int i = 0; i < productList.size(); i++) {
                            productNames[i] = productList.get(i).getName();
                        }
                        setPopupData(Constants.ITEM_TYPE.PRODUCT, productNames);
                    } else {
                        setPopupData(Constants.ITEM_TYPE.PRODUCT, null);
                    }
                }
            });
    }



    /**
     * 初始化医院
     */
    private void initHospitalList() {
        StockProto.get()
            .gethotel(0, "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<HospitalBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(HospitalBean bean) {
                     HospitalList = bean.data;

                    if (HospitalList != null) {
                        String[] productNames = new String[HospitalList.size()];
                        for (int i = 0; i < HospitalList.size(); i++) {
                            productNames[i] = HospitalList.get(i).title;
                        }
                        setPopupData(Constants.ITEM_TYPE.Hospital, productNames);
                    } else {
                        setPopupData(Constants.ITEM_TYPE.Hospital, null);
                    }
                }
            });
    }

    /**
     * 初始化科室
     */
    private void initDepartments(int hotel_id) {
        StockProto.get()
            .getDepartments(hotel_id, 0, "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<DepartmentsBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(DepartmentsBean bean) {
                      DepartmentsList = bean.data;
                    if (bean.data != null) {
                        String[] productNames = new String[bean.data.size()];
                        for (int i = 0; i < bean.data.size(); i++) {
                            productNames[i] = bean.data.get(i).title;
                        }
                        setPopupData(Constants.ITEM_TYPE.departments, productNames);
                    }
                }
            });
    }

    private void initUser(int hotel_id,int office_id) {
        StockProto.get()
            .getUser(0, office_id, "")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<UserBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.show(getActivity(), e.getMessage());
                }

                @Override
                public void onNext(UserBean bean) {
                      UserList = bean.data;
                    if (bean.data != null) {
                        String[] productNames = new String[bean.data.size()];
                        for (int i = 0; i < bean.data.size(); i++) {
                            productNames[i] = bean.data.get(i).name;
                        }
                        setPopupData(Constants.ITEM_TYPE.user, productNames);
                    }
                }
            });
    }

    /**
     * 设置下拉菜单数据
     */
    private void setPopupData(int item_type, String[] data) {
        switch (item_type) {
            case Constants.ITEM_TYPE.SPEC:
                mSpecPopup.setData(data, false);
                break;
            case Constants.ITEM_TYPE.PRODUCT:
                mProductPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.Hospital:
                mHospitalPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.departments:
                mDepartmentsPopup.setData(data, true);
                break;
            case Constants.ITEM_TYPE.user:
                mUserPopup.setData(data, false);
                break;
        }
    }
}
